package com.itrip.utils.sendmessage.maisend;


import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.security.Security;
import java.util.Date;
import java.util.Properties;

/**
 * 邮件发送类
 *
 * @author CL
 */
public class MailSender {

    public static boolean sendMail(String mailServerHost, String fromAddress, String password,
                                   String subject, String content, String type,
                                   String[] toAddress, String[] attachments) throws Exception {

        MailSenderInfo mailSenderInfo = new MailSenderInfo();
        mailSenderInfo.setMailServerHost(mailServerHost);
        mailSenderInfo.setFromAddress(fromAddress);
        mailSenderInfo.setUserName(fromAddress);
        mailSenderInfo.setPassword(password);
        mailSenderInfo.setToAddress(toAddress);
        mailSenderInfo.setSubject(subject);
        mailSenderInfo.setContent(content);
        mailSenderInfo.setType(type);
        mailSenderInfo.setAttachments(attachments);

        return sendMail(mailSenderInfo);
    }

    private static boolean sendMail(MailSenderInfo mailInfo) throws Exception {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

        MyAuthenticator authenticator = null;
        Properties pro = mailInfo.getProperties();

        authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());// 创建一个密码验证器,不是必须

        Session sendMailSession = Session.getDefaultInstance(pro, authenticator);  // 根据邮件会话属性和密码验证器构造一个发送邮件的session

        Message mailMessage = new MimeMessage(sendMailSession);      // 根据session创建一个邮件消息

        Address from = new InternetAddress(mailInfo.getFromAddress());      // 创建邮件发送者地址

        mailMessage.setFrom(from);      // 设置邮件消息的发送者

        //添加收件人地址
        Address[] to = toAddressInfo(mailInfo.getToAddress());//创建邮件的接收者地址，并设置到邮件消息中

        mailMessage.setRecipients(Message.RecipientType.TO, to);      // Message.RecipientType.TO属性表示接收者的类型为TO

        mailMessage.setSubject(mailInfo.getSubject());    // 设置邮件消息的主题

        mailMessage.setSentDate(new Date());      // 设置邮件消息发送的时间

        Multipart mainPart = new MimeMultipart();      // MiniMultipart类是一个容器类，包含MimeBodyPart类型的对象


        BodyPart mainContent = new MimeBodyPart();      // 创建一个包含主体内容的MimeBodyPart
        if (mailInfo.getType().equals("text")) {
            mainContent.setText(mailInfo.getContent());     //设置TEXT内容
        } else if (mailInfo.getType().equals("html")) {
            mainContent.setContent(mailInfo.getContent(), "text/html; charset=utf-8");   // 设置HTML内容
        } else {
            throw new Exception("邮件类型定义异常,请选择'text'或'html'");
        }

        mainPart.addBodyPart(mainContent);//添加主体内容到容器中

        //添加附件
        if (mailInfo.getAttachments() != null && mailInfo.getAttachments().length > 0) {
            attachementInfo(mainPart, mailInfo.getAttachments());
        }

        // 将MiniMultipart对象设置为邮件内容
        mailMessage.setContent(mainPart);
        // 发送邮件
        Transport.send(mailMessage);
        return true;
    }

    /**
     * 添加收件人地址
     *
     * @param toAddress
     * @return
     */
    private static Address[] toAddressInfo(String[] toAddress) throws AddressException {
        Address[] addArr = new InternetAddress[toAddress.length];
        for (int i = 0; i < toAddress.length; i++) {
            addArr[i] = new InternetAddress(toAddress[i]);
        }
        return addArr;
    }

    /**
     * 添加附件信息
     *
     * @param mainPart
     * @param attachments
     */
    private static void attachementInfo(Multipart mainPart, String[] attachments) throws MessagingException, UnsupportedEncodingException {
        for (int i = 0; i < attachments.length; i++) {
            // 创建一新的MimeBodyPart
            MimeBodyPart mdp = new MimeBodyPart();
            //得到文件数据源
            FileDataSource fds = new FileDataSource(attachments[i]);
            //得到附件本身并至入BodyPart
            mdp.setDataHandler(new DataHandler(fds));
            //得到文件名同样至入BodyPart
            mdp.setFileName(MimeUtility.encodeText(fds.getName()));
            //添加附件
            mainPart.addBodyPart(mdp);
        }
    }

}